import type { Song } from '../api/music';

const LOCAL_MUSIC_KEY = 'fitness_local_music';
const PLAYLISTS_KEY = 'fitness_playlists';

// 保存本地上传的音乐
export function saveLocalMusic(song: Song): void {
  try {
    // 获取已保存的本地音乐
    const localMusic = getLocalMusic();
    
    // 检查是否已存在相同ID的歌曲
    const existingIndex = localMusic.findIndex(item => item.id === song.id);
    
    if (existingIndex >= 0) {
      // 更新已存在的歌曲
      localMusic[existingIndex] = song;
    } else {
      // 添加新歌曲
      localMusic.push(song);
    }
    
    // 保存回本地存储
    localStorage.setItem(LOCAL_MUSIC_KEY, JSON.stringify(localMusic));
  } catch (error) {
    console.error('保存本地音乐失败:', error);
  }
}

// 获取所有本地上传的音乐
export function getLocalMusic(): Song[] {
  try {
    const musicJson = localStorage.getItem(LOCAL_MUSIC_KEY);
    if (musicJson) {
      return JSON.parse(musicJson);
    }
  } catch (error) {
    console.error('获取本地音乐失败:', error);
  }
  return [];
}

// 删除本地上传的音乐
export function deleteLocalMusic(id: string): boolean {
  try {
    const localMusic = getLocalMusic();
    const filteredMusic = localMusic.filter(song => song.id !== id);
    
    if (filteredMusic.length !== localMusic.length) {
      localStorage.setItem(LOCAL_MUSIC_KEY, JSON.stringify(filteredMusic));
      return true;
    }
  } catch (error) {
    console.error('删除本地音乐失败:', error);
  }
  return false;
}

// 播放列表相关类型
export interface Playlist {
  id: string;
  name: string;
  description: string;
  songIds: string[];
  createdAt: number;
  updatedAt: number;
}

// 创建播放列表
export function createPlaylist(name: string, description: string = ''): Playlist | null {
  try {
    const playlists = getPlaylists();
    
    // 创建新的播放列表
    const newPlaylist: Playlist = {
      id: Date.now().toString(),
      name,
      description,
      songIds: [],
      createdAt: Date.now(),
      updatedAt: Date.now()
    };
    
    playlists.push(newPlaylist);
    localStorage.setItem(PLAYLISTS_KEY, JSON.stringify(playlists));
    
    return newPlaylist;
  } catch (error) {
    console.error('创建播放列表失败:', error);
    return null;
  }
}

// 获取所有播放列表
export function getPlaylists(): Playlist[] {
  try {
    const playlistsJson = localStorage.getItem(PLAYLISTS_KEY);
    if (playlistsJson) {
      return JSON.parse(playlistsJson);
    }
  } catch (error) {
    console.error('获取播放列表失败:', error);
  }
  return [];
}

// 获取指定播放列表
export function getPlaylist(id: string): Playlist | null {
  try {
    const playlists = getPlaylists();
    return playlists.find(playlist => playlist.id === id) || null;
  } catch (error) {
    console.error('获取播放列表失败:', error);
    return null;
  }
}

// 更新播放列表
export function updatePlaylist(playlist: Playlist): boolean {
  try {
    const playlists = getPlaylists();
    const index = playlists.findIndex(item => item.id === playlist.id);
    
    if (index >= 0) {
      // 更新更新时间
      playlist.updatedAt = Date.now();
      
      playlists[index] = playlist;
      localStorage.setItem(PLAYLISTS_KEY, JSON.stringify(playlists));
      return true;
    }
  } catch (error) {
    console.error('更新播放列表失败:', error);
  }
  return false;
}

// 删除播放列表
export function deletePlaylist(id: string): boolean {
  try {
    const playlists = getPlaylists();
    const filteredPlaylists = playlists.filter(playlist => playlist.id !== id);
    
    if (filteredPlaylists.length !== playlists.length) {
      localStorage.setItem(PLAYLISTS_KEY, JSON.stringify(filteredPlaylists));
      return true;
    }
  } catch (error) {
    console.error('删除播放列表失败:', error);
  }
  return false;
}

// 将歌曲添加到播放列表
export function addSongToPlaylist(playlistId: string, songId: string): boolean {
  try {
    const playlist = getPlaylist(playlistId);
    
    if (playlist) {
      // 检查歌曲是否已在播放列表中
      if (!playlist.songIds.includes(songId)) {
        playlist.songIds.push(songId);
        playlist.updatedAt = Date.now();
        
        return updatePlaylist(playlist);
      }
      return true; // 歌曲已存在于播放列表中
    }
  } catch (error) {
    console.error('添加歌曲到播放列表失败:', error);
  }
  return false;
}

// 从播放列表中删除歌曲
export function removeSongFromPlaylist(playlistId: string, songId: string): boolean {
  try {
    const playlist = getPlaylist(playlistId);
    
    if (playlist) {
      const index = playlist.songIds.indexOf(songId);
      
      if (index >= 0) {
        playlist.songIds.splice(index, 1);
        playlist.updatedAt = Date.now();
        
        return updatePlaylist(playlist);
      }
      return true; // 歌曲不在播放列表中
    }
  } catch (error) {
    console.error('从播放列表中删除歌曲失败:', error);
  }
  return false;
} 